<template>
	<coreshop-page title="接龙详情" mode="left" bgColor="#D33123" titleColor="#fff" showLoginModalDom needLoadingPage
		:loadingPage="loadingPage">
		<view class="layout-solitaire-box">
			<view class="config-box">
				<image class="img" :src="shopConfigStore?.config?.shopLogo"></image>
				<view class="store-box">
					<view class="name">{{ shopConfigStore?.config?.shopName }}</view>
					<view class="tit">{{ shopConfigStore?.config?.shareTitle }}</view>
				</view>
				<view class="btn-phone" @click="hanldePhoneCallStore">
					<view class="tit">联系商家</view>
				</view>
			</view>
			<!-- 接龙内容 -->
			<view class="solitaire-info">
				<view class="title">{{ state.solitaireInfo?.title }}</view>
				<view class="time">
					{{ timeFormat(state.solitaireInfo?.createTime, 'yyyy年mm月dd日') }} 发布截止 {{
                        timeFormat(state.solitaireInfo?.endTime, 'yyyy年mm月dd日') }}
				</view>
				<view class="tag-box">
					<view class="tag count" v-if="state.solitaireInfo?.minDeliveryPrice > 0">{{
                        state.solitaireInfo?.minDeliveryPrice }}元起送
					</view>
					<view class="tag nums" v-if="state.solitaireInfo?.startBuyPrice > 0">{{
                        state.solitaireInfo?.startBuyPrice }}元起购
					</view>
				</view>
				<view class="content">
					<uv-parse :content="state.solitaireInfo?.contentBody"></uv-parse>
				</view>
				<view class="share-box" @click="handleToggleShowShare">
					<uv-icon name="share-fill" color="#fff" size="20"></uv-icon>
				</view>
			</view>
			<!-- 接龙商品 -->
			<view class="goods-box">
				<view class="item-box" v-for="item, index in state.goodsData" :key="item.id">
					<coreshop-goods-card type="horizontal" imgHeight="160rpx" imgWidth="160rpx"
						:goodsData="hanldeCombinationGoodsData(item)">
						<template #goodPrice>
							<view class="price-box">
								<view class="price-info">
									<view class="price">￥{{ item.price }}</view>
									<view class="line-price">￥{{ item.productObj.mktprice }}</view>
								</view>
								<uv-number-box :min="0" v-model="item.num"
									@change="handleChangeGoodsNum($event, index)"></uv-number-box>
							</view>
						</template>
					</coreshop-goods-card>
					<view class="stockNo" v-if="item.stockNo">库存不足</view>
					<view class="stockTension" v-if="item.stockTension">库存紧张</view>
				</view>
			</view>
			<!-- 接龙清单 -->
			<view class="solitaire-order">
				<view class="title">接龙清单</view>
				<view v-if="state.recordData.length > 0">
					<view class="item-box" v-for="item, index in state.recordData" :key="index">
						<view class="rank">{{ state.recordData.length - index }}</view>
						<view class="order-info">
							<view class="name-sku">
								<view class="name-box">
									<image class="img" :src="item.avatarImage"></image>
									<text class="name">{{ item.nickName }}</text>
								</view>
								<view class="sku">{{ item.productSku }}</view>
							</view>
							<view class="time-num">
								<view class="time">{{ timeFormat(item.create, 'mm月dd日') }}</view>
								<view class="num">x{{ item.nums }}</view>
							</view>
						</view>
					</view>
				</view>
				<view v-else>
					<coreshop-empty :mode="EmptyEnum.data" text="暂无接龙"></coreshop-empty>
				</view>
			</view>
			<!-- 底部按钮 -->
			<view class="goods-detail-bottom-tabbar">
				<view class="btn-box">
					<view class="total">
						<view class="tit">合计:</view>
						<view class="price">￥{{ state.totalprice }}</view>
					</view>
					<view class="buy" @click="handleBuyNow">立即结算</view>
				</view>
			</view>

			<!-- 分享弹框 -->
			<CoreshopShare :show="state.showShare" :shareType="ShareEnum.solitaire"
				:goodsDetailData="state.solitaireInfo" @handleClosePopup="handleToggleShowShare"></CoreshopShare>
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { onLoad, onShareAppMessage, onShareTimeline, onPullDownRefresh } from '@dcloudio/uni-app';
	import { querySolitaireDetail, queryAddCart, queryRemoveCart } from '@/core/api';
	import { ShareClientEnum, ShareModelEnum, ShareEnum, EmptyEnum, PaymentTypeEnum, AddCartEnum } from '@/core/enum';
	import type { Response } from '@/core/models';
	import { shareUrl } from '@/core/consts'
	import { useShopConfigStore, useLoginStore } from '@/core/store';
	import { handleShowToast, handleRouteNavigateTo, getShareUrl } from '@/core/utils';
	import { timeFormat } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
	import CoreshopShare from '@/components/coreshop-share/coreshop-share.vue';
	import { useLoadingFn } from '@/core/hooks';

	interface QueryParams {
		id : number;
	}

	/** 登录store */
	const _useLoginStore = useLoginStore();

	/** 获取项目配置 */
	const shopConfigStore = useShopConfigStore();

	const state = reactive<{
		id : number;
		solitaireInfo : any;
		goodsData : Array<any>;
		recordData : Array<any>;
		totalprice : number;
		shareUrl : string;
		showShare : boolean;
	}>({
		id: 0,
		solitaireInfo: {},
		goodsData: [],
		recordData: [],
		totalprice: 0,
		shareUrl: "",
		showShare: false,
	});

	const loadingPage = ref(true);
	const handleGetGoodsDetail = useLoadingFn(getGoodsDetail, loadingPage);
	onLoad((query : QueryParams) => {
		state.id = Number(query.id);
		/** 获取商品详情 */
		handleGetGoodsDetail();
	});

	onPullDownRefresh(async () => {
		await handleGetGoodsDetail();
		uni.stopPullDownRefresh();
	});


	async function getGoodsDetail() {
		const solitaireData : Response<any> = await querySolitaireDetail({ id: state.id });
		if (solitaireData.status) {
			state.solitaireInfo = solitaireData.data.model;
			state.goodsData = solitaireData.data.items.map((item : any) => {
				item['num'] = 0;
				item['addCardId'] = 0;
				return item;
			});
			state.recordData = solitaireData.data.record;
		} else {
			handleShowToast(solitaireData.msg)
		}

		state.shareUrl = await getShareUrl({
			client: ShareClientEnum.wxMiNiProgram,
			url: shareUrl,
			type: ShareModelEnum.url,
			page: ShareEnum.solitaire,
			params: {
				id: state.solitaireInfo.id
			}
		})
	}

	/** 步进器变化 */
	const handleChangeGoodsNum = async (e : any, index : number) => {
		if (e.value > 0) {
			const addCart : Response<number> = await queryAddCart({
				productId: state.goodsData[index].productId,
				nums: e.value,
				type: AddCartEnum.buy,
				cartType: PaymentTypeEnum.solitaire,
				objectId: state.id,
			});
			if (addCart.status) {
				state.goodsData[index].addCardId = addCart.data;
			} else {
				handleShowToast(addCart.msg)
			}
		} else {
			await queryRemoveCart({
				id: state.goodsData[index].addCardId,
			})
		}
		getGoodsTotalMoney();
	}

	/** 获取商品总额 */
	const getGoodsTotalMoney = () => {
		let totalprice = 0;
		state.goodsData.forEach((item : any) => {
			totalprice += (item.price * item.num)
		});
		state.totalprice = totalprice;
	}

	// 组合商品数据传入组件
	const hanldeCombinationGoodsData = (item : any) => {
		return {
			image: item.goodObj.image,
			name: item.goodObj.name,
			brief: item.productObj.spesDesc,
		}
	}

	/**立即购买 */
	const handleBuyNow = () => {
		_useLoginStore.checkLogin(() => {
			if (state.totalprice == 0) {
				handleShowToast('请先选择商品');
				return;
			}
			if (state.totalprice < state.solitaireInfo.startBuyPrice) {
				handleShowToast(`最小购买价格为${state.solitaireInfo.startBuyPrice}元,请增加购买产品`)
				return true
			}
			let ids : Array<number> = [];
			state.goodsData.forEach((item : any) => {
				if (item.num > 0) {
					ids.push(item.addCardId)
				}
			});
			if (ids.length > 0) {
				handleRouteNavigateTo(`/pages/order/submit/submit?orderType=${PaymentTypeEnum.solitaire}&objectId=${state.id}&cartIds=${ids.join(',')}`)
			} else {
				handleShowToast('请先选择商品');
			}
		});
	}

	/** 联系商家 */
	const hanldePhoneCallStore = () => {
		if (shopConfigStore?.config?.shopMobile) {
			uni.makePhoneCall({
				phoneNumber: shopConfigStore?.config?.shopMobile
			});
		}
	}

	/** 分享弹框显示与否 */
	const handleToggleShowShare = () => {
		_useLoginStore.checkLogin(() => {
			state.showShare = !state.showShare;
		})
	}

	/** 分享 */
	onShareAppMessage(() => {
		return {
			title: state.solitaireInfo.title,
			imageUrl: state.solitaireInfo.thumbnail,
			path: state.shareUrl
		}
	});
	onShareTimeline(() => {
		return {
			title: state.solitaireInfo.title,
			imageUrl: state.solitaireInfo.thumbnail,
			path: state.shareUrl
		}
	});
</script>
<style lang="scss" scoped>
	@import './detail.scss';
</style>